# Create your views here.
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from icssite.cms.models import Menu,Catalog,Article


menus=Menu.objects.filter(online=True)
def home(request):

    """
    Display homepage
    """
    return render_to_response('index.html',{'menus':menus},context_instance=RequestContext(request))

def catalog(request,mid):
    """
    load catalog page.
    """
    menus=Menu.objects.filter(online=True)

    try:
        mid=int(mid)
        menu=Menu.objects.get(id=mid)
        catalogs=menu.catalog_set.all()
        articles=catalogs[0].article_set.all()
        request.session['catalogs']=catalogs
    except ValueError:
        raise Http404()
    request.session['mid']=mid
    if len(articles)>1:
        return render_to_response('catalog.html', dict(articles=articles,catalogs=catalogs, menus=menus, header=menu),context_instance=RequestContext(request))
    else:
        article=articles[0]
        return render_to_response('article.html', dict(article=article,catalogs=catalogs, menus=menus, catalog=catalog),context_instance=RequestContext(request))



def list_articles(request,cid):
    """
    load article list of catalog
    """
    try:
        cid=int(cid)
        catalog=Catalog.objects.get(id=cid)
        menu=catalog.menu
        catalogs=menu.catalog_set.all()
        articles=catalog.article_set.all()
        request.session['catalogs']=catalogs
    except ValueError:
        raise Http404()
    return render_to_response('catalog.html', dict(articles=articles, catalogs=catalogs,menus=menus, header=catalog),context_instance=RequestContext(request))
def get_article(request,rid):
    """
    load article page
    """
    try:
        print 'rid',rid
        rid=int(rid)
        article=Article.objects.get(id=rid)
        catalogs=request.session["catalogs"]
        print 'title:',article.title


    except ValueError:
        raise Http404()
    return render_to_response('article.html', dict(article=article,catalogs=catalogs, menus=menus, catalog=catalog),context_instance=RequestContext(request))
